package edu.hubu.commons;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Properties;
import java.util.UUID;

/**
 * @author moonlan
 * @date 2020/10/18 上午11:38
 */
public class SnowflakeId implements IdentifierGenerator, Configurable {
    private String prefix;

    @Override
    public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws
                                                                                                              HibernateException {
        return getId();
    }

    @Override
    public boolean supportsJdbcBatchInserts() {
        return false;
    }

    @Override
    public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException {
        this.prefix = properties.getProperty("prefix"); //	实体类中@Parameter注解，根据键值获取value
        prefix += "-" + Calendar.getInstance().get(Calendar.YEAR);
    }

    public String getId() {
        synchronized (SnowflakeId.class) {
            String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
            return prefix + "-" + uuid;
        }
    }
}
